<template>
  <view class="aiReplay">
    <u-popup
      :show="show"
      mode="bottom"
      :round="6"
      bgColor="#e2eaff"
      :closeOnClickOverlay="true"
      :closeable="false"
      @close="close"
      :safeAreaInsetBottom="true"
    >
      <view class="popCenter">
        <view class="row-center" style="height: 124rpx">
          <view class="title">AI回复</view>
          <image
            class="closeIcon"
            src="@/pagesA/static/images/chat/ai_close.png"
            @tap="close"
          ></image>
        </view>
        <scroll-view
          class="content"
          scroll-y="true"
          enable-flex="true"
          scroll-with-animation="true"
        >
          <kkLoading class="kkLoading" v-if="showLoading" />

          <scroll-view
            style="
              width: calc(100% - 48rpx);
              height: calc(100%);
              padding: 24rpx;
            "
            v-if="aiResponseContent && isKatexStr(aiResponseContent)"
            scroll-x="true"
          >
            <kkKatex :data="aiResponseContent"></kkKatex>
          </scroll-view>
          <!-- <view
            v-if="aiResponseContent && !isKatexStr(aiResponseContent)"
            class="content-text textWrap"
            v-html="aiResponseContent"
          ></view> -->
          <view class="aiMarkdown">
            <ua-markdown
              v-if="aiResponseContent && !isKatexStr(aiResponseContent)"
              :source="aiResponseContent"
            />
          </view>

          <kk-no-data
            v-if="!showLoading && !aiResponseContent && aiResponseEnd"
            class="noDataPage"
          />
        </scroll-view>
        <view class="bottom">
          <view
            class="bottom-btn"
            :class="{ 'bottom-btnDisable': !aiResponseEnd }"
            @tap="copyAiContent"
            >复制到回复框</view
          >
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { isKatexStr } from "@/pagesA/utils/util";
import kkKatex from "@/pagesA/components/kkKatex/index.vue";
import UaMarkdown from "@/pagesA/components/ua-markdown/ua-markdown.vue";
import kkLoading from "@/components/common/KKContainer/loading.vue";
import { buildUUID } from "@/utils/util";
import { appConfig } from "@/config";
import { getKKToken } from "@/utils/storageUtil";
import createEncryption from "@/utils/createEncryption";
import { version } from "../../../../package.json";
import { isJSON } from "@/utils/util";
import utf8Array2Str from "utf8array2str";

const props = defineProps({
  show: {
    type: Boolean,
    default: true,
  },

  round: {
    type: Number,
    default: 8,
  },
  // 标题
  title: {
    type: String,
    default: "",
  },
  //自定义中间区域
  customerCenter: {
    type: Boolean,
    default: false,
  },
  // `已知函数 $f(x) = \\frac{x^{2} + 2x - 3}{x - 1}$，则 $\\lim_{\\Delta x \\longrightarrow 0}\\frac{f(1 + \\Delta x) - f(1)}{\\Delta x} = \\underline{\\phantom{0}}$`
  subTitle: {
    type: String,
    default: "确定",
  },
  aiReplayRequestParam: {
    type: Object,
    default() {
      return {};
    },
  },
});

const showLoading = ref(false);

// 按钮关闭
const close = () => {
  emit("close");
};

const cancel = () => {
  emit("cancel");
};

const submit = () => {
  emit("submit");
};

const copyAiContent = () => {
  if (aiResponseEnd.value && aiResponseContent.value) {
    emit("copyAiContent", aiResponseContent.value);
  }
};

const getEncryptionData = (data: any, method: string) => {
  if (method.toLowerCase() === "post") {
    const postBodyEncryption = createEncryption("b2814071841", "awo6ureum8bn");
    data = postBodyEncryption(getKKToken(), data);
  }
  return data;
};

const getRequestUrl = (url: string) => {
  return appConfig.baseUrl + url;
};

// AI回复内容
const aiResponseContent = ref("");
const aiResponseEnd = ref(false);
// AI回复请求
const aiReplayRequest = () => {
  // props.aiReplayRequestParam.messages = [
  //   {
  //     type: "text",
  //     content: "数学平方差公式如何推导",
  //     role: "student",
  //   },
  // ];
  setTimeout(() => {
    if (!aiResponseContent.value) {
      showLoading.value = true;
    }
  }, 400);
  const systemInfo = uni.getSystemInfoSync();
  const requestTask = wx.request({
    method: "POST",
    timeout: 30000,
    enableChunked: true,
    responseType: "text",
    url: getRequestUrl("/kukeanswerhive/interractive/pc/getAiResponseProt"),
    data: getEncryptionData(props.aiReplayRequestParam, "POST"),
    header: {
      "Content-Type": "application/json",
      "kk-request-id": `${buildUUID()}${new Date().getTime()}`,
      "kk-version": version,
      "kk-from": "wechat-app",
      "kk-os": systemInfo.osName || "",
      "kk-modle": systemInfo.model || "",
      "kk-ip": "",
      "tenant-id": "",
      "org-id": "",
      "kk-token": getKKToken(),
    },
  });
  requestTask.onHeadersReceived((res: any) => {});
  requestTask.onChunkReceived((res: any) => handleChunk(res));
};

const handleChunk = (res: any) => {
  const arrayBuffer = res.data;
  const uint8Array = new Uint8Array(arrayBuffer);
  // const str = new TextDecoder("utf-8").decode(uint8Array);
  const str = utf8Array2Str(uint8Array);

  const lines = str.split("data:");
  lines.forEach((line) => {
    if (!line.trim()) {
      return;
    }
    if (!line.includes(`:welcome`)) {
      if (isJSON(line)) {
        const json = JSON.parse(line);
        aiResponseContent.value = aiResponseContent.value + json.content;
        aiResponseEnd.value = json.end;
        if (aiResponseEnd.value) {
          console.log("流水请求结果：", aiResponseContent.value);
        }
        if (aiResponseContent.value) {
          showLoading.value = false;
        }
      } else {
        showLoading.value = false;
        console.log("无法json解析：", line);
      }
    } else {
    }
  });
};

onMounted(() => {
  aiReplayRequest();
});

const emit = defineEmits(["close", "submit", "cancel", "copyAiContent"]);
</script>

<style lang="scss" scoped>
.aiReplay {
  .popCenter {
    display: flex;
    flex-direction: column;
    background: linear-gradient(209deg, #a1cdff 0%, #e5edff 76%, #e5edff 100%),
      radial-gradient(
        20% 56% at 36% 62%,
        #c6c6f7 0%,
        rgba(199, 207, 251, 0) 85%
      ),
      #e5edff;
    border-radius: 6px;
    width: calc(100vw);
    .title {
      padding-left: 24rpx;
      height: 124rpx;
      font-weight: 500;
      font-size: 36rpx;
      color: #111111;
      line-height: 124rpx;
    }
    .closeIcon {
      margin-left: auto;
      margin-right: 24rpx;
      width: 44rpx;
      height: 44rpx;
    }
    .content {
      margin-top: 16rpx;
      margin-left: 24rpx;
      margin-right: 24rpx;
      margin-bottom: -54rpx;
      padding-bottom: 54rpx;
      width: calc(100vw - 48rpx);
      max-height: calc(65vh);
      min-height: calc(50vh);
      background: rgba(255, 255, 255, 0.8);
      box-shadow: -4rpx -4rpx 20rpx 0rpx rgba(62, 141, 255, 0.1),
        4rpx 4rpx 20rpx 0rpx rgba(117, 59, 255, 0.1);
      border-radius: 12rpx;
      border: 2rpx solid;
      border-image: linear-gradient(
          89deg,
          rgba(61, 142, 255, 1),
          rgba(120, 53, 255, 1)
        )
        2 2;
      &-text {
        padding: 24rpx;
      }
      .noDataPage {
        min-height: calc(50vh);
      }

      .aiMarkdown {
        padding: 24rpx;
        font-weight: 400;
        font-size: 28rpx;
        color: #333333;
        line-height: 42rpx;
      }
      .kkLoading {
      }
    }
    .bottom {
      background: #e2eaff;
      z-index: 9;
      height: 112rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      &-btn {
        width: 341rpx;
        height: 88rpx;
        background: linear-gradient(90deg, #3d8eff 0%, #743cff 100%);
        border-radius: 16rpx;
        font-weight: 500;
        font-size: 32rpx;
        color: #ffffff;
        line-height: 88rpx;
        text-align: center;
      }
      &-btnDisable {
        opacity: 0.5;
      }
    }
  }
}
</style>
